/*
 * ImageFactory.cpp
 *
 *  Created on: 2011-1-17
 *      Author: Administrator
 */

#include "ImageFactory.h"

CImageFactory* CImageFactory::getInstance()
	{
	if (iInstance == NULL)
		{
		iInstance = new CImageFactory();
		}
	return iInstance;
	}

void CImageFactory::ReleaseInstance()
	{
	if (iInstance)
		{
		delete iInstance;
		iInstance = NULL;
		}
	}

CImageFactory::CImageFactory()
	{
	}

CImageFactory::~CImageFactory()
	{
	iImages.ResetAndDestroy();
	}

CImage* CImageFactory::getImageL(const TDesC& aFileName)
	{
	CImage* Image = NULL;
	for(TInt i = 0; i < iImages.Count(); i++)
		{
		Image = iImages[i];
		if (Image->ImageFileName().CompareF(aFileName) ==0)
			{
			Image->AddRefCount();
			return Image;
			}
		}
	Image = new CImage();
	TFileName FullName;
	FullName.Append(iImagePath);
	FullName.Append(aFileName);
	Image->SetImageFileName(aFileName);
	Image->ReadImageFromFileL(FullName);
	iImages.AppendL(Image);
	return Image;
	}

void CImageFactory::RemoveImage(CImage* aImage)
	{
	if (aImage)
		{
		TInt index = iImages.Find(aImage);
		if (index >= 0)
			{
			iImages.Remove(index);
			}
		if (iImages.Count() == 0)
			ReleaseInstance();
		}
	}

void CImageFactory::ReleaseImage(CImage* aImage)
	{
	if (aImage)
		{
		if (aImage->iRefCount > 1)
			{
			aImage->DecRefCount();
			}
		else
			{
			TInt index = iImages.Find(aImage);
			if (index >= 0)
				{
				iImages.Remove(index);
				}
			delete aImage;
			aImage = NULL;
			}
		if (iImages.Count() == 0)
			ReleaseInstance();
		}
	}

void CImageFactory::setImagePath(const TDesC& aPath)
	{
	iImagePath.Zero();
	iImagePath.Append(aPath);
	}

TFileName CImageFactory::ImagePath()
	{
	return iImagePath;
	}
